﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Utilities;
using System.Configuration;

using System.Data.SqlClient;
using SpringWaterDataAccess;
namespace sow
{
	/// <summary>
	/// Summary description for bloggercontent.
	/// </summary>
	public partial class bloggercontent : System.Web.UI.Page
	{
		protected string postID = "";
		protected int totalRecords = 0;	
		protected int pageNumber = 0;
		protected int totalPages = 0;
		protected string userID = "";
		protected int year = 0;
		protected int month = 0;
		protected int day = 0;
		protected string sReads = "1";
		protected string sPartner = "Unknown";
		protected string sURL = "www.SpringOfWater.net";
		protected string sURLName = "泉源";
		protected string sCreateUser = "";
		protected string sRecommendBy = "";
		
	

		protected void Page_Load(object sender, System.EventArgs e)
		{
			 
			postID = Request.QueryString["PostID"];
			userID = Request.QueryString["UserID"];
			year = Convert.ToUInt16(Request.QueryString["Year"]);
			month =  Convert.ToUInt16(Request.QueryString["Month"]);
			day = Convert.ToUInt16(Request.QueryString["Day"]);

			pageNumber = Convert.ToInt16(Request.QueryString["Page"]);

			System.Web.HttpCookie emailCookie = Request.Cookies["Email"];
			TextBox3.Enabled = (emailCookie != null && 
				            emailCookie.Value != "");
			
			// If page number is not passed, treat as the first page
			if (pageNumber == 0)
				pageNumber=1;

            // Put user code to initialize the page here
			if (!IsPostBack) 
			{
				//----------------------------------------------
				//Added By zxh 7/14/2006
//				IncreaseClicks(Convert.ToInt64(postID));

				//Commented out for now By ZHisong
				//DataSet ds = GetArticleByPostID(Convert.ToInt64(postID));
				//if(ds.Tables[0].Rows.Count > 0)
				//{
				//	DataRow dr = ds.Tables[0].Rows[0];
				//	this.Literal_UserArticles.Text = "<a href='../search/AllArticles.aspx?id=" + dr["UserID"].ToString() + "&name=" + Server.UrlEncode(dr["NickName"].ToString()) + "' target=_blank>所有 " + dr["NickName"].ToString() + " 的文章</a>";
				//}
				//--------------------------------------------
			}
				BindData();		
		}


		private void BindData() 
		{

			ForumDataAccess da = new ForumDataAccess();

		 	int uid = Convert.ToUInt16(Request.QueryString["UserID"]);

			int startRecordNumber = (pageNumber - 1)*10 + 1;

			DataSet MyRepeaterDataSource;
				
			int pid = Convert.ToUInt16(Request.QueryString["PostID"]);
		    da.IncreaseClicks(pid); 		
			
			DataList4.DataSource = da.getRepliesByPostID(pid,0,0,
				out totalRecords,"blog", "Active", 0, "CreateDate");


			DataList4.DataBind();

			MyRepeaterDataSource = da.GetPostDetailByPostID(postID);
				
			// We need to get reply numbers for each post in the table
			DataTable postDataTable = MyRepeaterDataSource.Tables[0];
			
			//Add code for retriving NumberOfVisits, OriginAuthor, and URL. --JERRYC
			if (postDataTable.Rows.Count > 0)
			{
				sReads = postDataTable.Rows[0]["NumberOfVisits"].ToString();
				sPartner = postDataTable.Rows[0]["OriginAuthor"].ToString();
				sURL = postDataTable.Rows[0]["PartnerURL"].ToString();
				sURLName = postDataTable.Rows[0]["PartnerURLName"].ToString();
				if (postDataTable.Rows[0]["CreateUser"] != Convert.DBNull) 
				{
					sCreateUser = UserObject.getUserName(postDataTable.Rows[0]["CreateUser"]);
				}
			}

			postDataTable.Columns.Add(new DataColumn("ReplyNumbers",typeof(string)));
			foreach (DataRow row in postDataTable.Rows)
			{
				row["ReplyNumbers"] = getPostNumberOfReplies(Convert.ToString(row["PostID"]));
			}
				
			MyRepeater.DataSource =  postDataTable;			
			MyRepeater.DataBind();			
			
			DateTime curr = DateTime.Now;
			DateTime start = DateTime.Parse("2005/09/01");

			ArrayList dtList = new ArrayList();
			for (DateTime dt = start; 
				dt <= curr; dt = dt.AddMonths(1))
			{
				dtList.Add(dt);
			}
			dtList.Reverse();

//			DataList3.DataSource = dtList;
//			DataList3.DataBind();

			DataSet userDS = UserObject.GetUserByID(Convert.ToUInt16(userID));

//			DataList5.DataSource = userDS;
//			DataList5.DataBind();

//			DataList6.DataSource = userDS;
//			DataList6.DataBind();

		}
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.MyRepeater.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.MyRepeater_ItemDataBound);

		}
		#endregion
		public string getPostNumberOfReplies(string postID) 
		{
			ForumDataAccess da = new ForumDataAccess();

			return Convert.ToString(da.getPostNumberOfReplies(
				Convert.ToUInt16(postID),"blog","Active"));
		}

		 

		private void MyRepeater_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
		
		}

		protected void Button1_Click(object sender, System.EventArgs e)
		{
			
		}

		//---------------------------------------------------------------
		//-- Begin -- Added By zxh 7/14/2006

		private DataSet GetArticleByPostID(long PostID)
		{
			string storedprocedure = "sp_GetArticleByPostID";
			SqlCommand cmd = new SqlCommand(storedprocedure);
			cmd.CommandType = CommandType.StoredProcedure;

			SqlParameter paraPostID = cmd.CreateParameter();
			paraPostID.SqlDbType = SqlDbType.Int;
			paraPostID.ParameterName = "@PostID";
			paraPostID.Value = PostID;
			cmd.Parameters.Add(paraPostID);

			SqlConnection cn = new SqlConnection();
			cn.ConnectionString =  ConfigurationSettings.AppSettings["DBConnStr"];
			cn.Open();

			cmd.Connection = cn;
			SqlDataAdapter da = new SqlDataAdapter(cmd);
			DataSet ds = new DataSet();
			da.Fill(ds);
			cn.Close();

			return ds;
		}

		private string GetArticleURL(string PostID)
		{
			string textstr = "select * from article where postid=" + PostID;
			SqlCommand cmd = new SqlCommand(textstr);
			cmd.CommandType = CommandType.Text;

			SqlConnection cn = new SqlConnection();
			cn.ConnectionString =  ConfigurationSettings.AppSettings["DBConnStr"];
			cn.Open();

			cmd.Connection = cn;
			SqlDataAdapter da = new SqlDataAdapter(cmd);
			DataSet ds = new DataSet();
			da.Fill(ds);
			cn.Close();

			string returnstr = "";
			if(ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]["URL"] != null)
				returnstr = ds.Tables[0].Rows[0]["URL"].ToString();
			return returnstr;
		}

		private void IncreaseClicks(long postID) 
		{
			string storeProcedureName = "sp_IncreaseClicks"; 
			SqlCommand cmd = new SqlCommand(storeProcedureName);
			cmd.CommandType = CommandType.StoredProcedure;

			SqlParameter postIDPara = cmd.CreateParameter();
			postIDPara.SqlDbType = SqlDbType.Int;
			postIDPara.ParameterName = "@PostID";
			postIDPara.Value = postID;
			cmd.Parameters.Add(postIDPara);

			SqlConnection cn = new SqlConnection();
			cn.ConnectionString =  ConfigurationSettings.AppSettings["DBConnStr"];
			cn.Open();

			cmd.Connection = cn;
			cmd.ExecuteNonQuery();

			cn.Close();
		}


		private bool VoteArticle(long PostID, string flag)
		{
			SqlCommand cmd = new SqlCommand("sp_VoteArticle");
			cmd.CommandType = CommandType.StoredProcedure;

			SqlParameter paraPostID = cmd.CreateParameter();
			paraPostID.SqlDbType = SqlDbType.Int;
			paraPostID.ParameterName = "@PostID";
			paraPostID.Value = PostID;
			cmd.Parameters.Add(paraPostID);

			SqlParameter paraflag = cmd.CreateParameter();
			paraflag.SqlDbType = SqlDbType.VarChar;
			paraflag.ParameterName = "@flag";
			paraflag.Value = flag;
			cmd.Parameters.Add(paraflag);

			SqlConnection cn = new SqlConnection();
			cn.ConnectionString =  ConfigurationSettings.AppSettings["DBConnStr"];
			cn.Open();

			cmd.Connection = cn;
			cmd.ExecuteNonQuery();
			
			cn.Close();

			return true;
		}

		protected void Button_yes_Click(object sender, System.EventArgs e)
		{
			HttpCookie voteCookie = Request.Cookies["VoteArticle" + postID];
			if(voteCookie == null)
			{
				VoteArticle(Convert.ToInt64(postID), "1");
				voteCookie = new HttpCookie("VoteArticle" + postID, "1");
				voteCookie.Expires = DateTime.MaxValue;
				Response.Cookies.Add(voteCookie);
				this.Button_yes.Attributes["onclick"] = "alert('在此之前，你已经对本篇文章投了对你“有”帮助一票！'); return false;";
				this.Button_no.Attributes["onclick"] = "alert('在此之前，你已经对本篇文章投了对你“有”帮助一票！'); return false;";
			}
		}

		protected void Button_no_Click(object sender, System.EventArgs e)
		{
			HttpCookie voteCookie = Request.Cookies["VoteArticle" + postID];
			if(voteCookie == null)
			{
				VoteArticle(Convert.ToInt64(postID), "0");
				voteCookie = new HttpCookie("VoteArticle" + postID, "0");
				voteCookie.Expires = DateTime.MaxValue;
				Response.Cookies.Add(voteCookie);
				this.Button_yes.Attributes["onclick"] = "alert('在此之前，你已经对本篇文章投了对你“没有”帮助一票！'); return false;";
				this.Button_no.Attributes["onclick"] = "alert('在此之前，你已经对本篇文章投了对你“没有”帮助一票！'); return false;";
			}
		}

		private void MyRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
		{
			if(e.Item.ItemIndex < 0)
				return;

			string url = GetArticleURL(postID);
			if(url.Trim() != "")
			{
				//Literal literal = (Literal)e.Item.FindControl("Literal_ArticleURL");
				//literal.Text = "文章URL：<a href='" + url + "' target=_blank>" + url + "</a>";
				Response.Redirect(url);
				//literal.Text += "<script language=javascript>window.open('" + url + "');</script>";
			}
		}

        protected void Button1_Click1(object sender, EventArgs e)
        {

            ForumDataAccess da = new ForumDataAccess();
            string forumID = "";

            if (Request.Cookies["Email"] == null)
            {
                Response.Redirect("index.aspx?message=请先登录");
            }

            DataSet ds = UserObject.GetUser(Request.Cookies["Email"].Value);
            int uid = Convert.ToUInt16(ds.Tables[0].Rows[0]["UserID"]);

            da.InsertPost(Convert.ToUInt16(postID), 43,
                "", TextBox3.Text, uid, "", "blog", out forumID);

            BindData();
            TextBox3.Text = "";
            CacheHelper cacheHelper = new CacheHelper();
            cacheHelper.CleanAllCache();
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            TextBox3.Text = "";
        }

		//------------------------------------------------------------------------
	}
}
